<template>
    <van-nav-bar
  title="购物车"
  left-text="返回"
  left-arrow
  @click-left="onClickLeft"
/>
   <div class="cart-container">
   <van-card
   v-for="item in cartList"
   :key="item.proid"
   class="card"
  :num="item.num"
  :price="item.originprice"
  :title="item.proname"
  :thumb="item.img1"
>
  <template #footer>
    <van-button size="mini" @click="reduceNum(item.proid)">-</van-button>
    <van-button size="mini" @click="addNum(item.proid)">+</van-button>
    <van-button size="mini" @click="Sc(item.cartid)">删除</van-button>
  </template>
</van-card>
   </div>
  <van-submit-bar
    :price="cartList.reduce((pre, item) => pre + item.originprice * item.num, 0) * 100"
    button-text="提交订单"
    
    class="submit-bar"
  />
</template>

<script>
import { cartDelRequest, getCartListRequest } from '../../api/cartApi'

export default {
    data() {
        return {

            cartList: []
        }
    },
    methods: {
     onClickLeft(){
        this.$router.back()
     },

     addNum(proid){
        this.cartList.forEach(item => {
            if(item.proid == proid){
                item.num++
            }
        })
     },
     reduceNum(proid){
        this.cartList.forEach(item => {
            if(item.proid == proid){
                if(item.num > 1){
                    item.num--
                }
            }
        })
     },
     async Sc(cartid){
        try{
            const confirmDelete=confirm('确定删除吗?')
            if(!confirmDelete) return;

            const response=await cartDelRequest(cartid)
            this.cartList = this.cartList.filter(item => item.cartid !== cartid);
        }catch(error){
            console.error('删除购物车失败:', error);
        }
     },
    },
    created() {
        getCartListRequest().then(res => {
            console.log(res.data);
            this.cartList = res.data.data
            //查看图片
            // console.log(this.cartList[0].img1);
            
        })
    },
    mounted() {
        //  getCartListRequest(this.userid).then(res => {
        //         console.log(res.data);
        //         this.cartList = res.data.data
        //     })
    }
}

</script>




<style>


.cart-container {
    padding-bottom: 80px; /* 为底部提交订单按钮留出空间 */
}
.card {
    margin-bottom: 20px;
    margin-top: 20px;
    width: 95%;
    margin-left: auto;
    margin-right: auto;
}
.submit-bar{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin-bottom: 0;
    padding: 10px;
    background-color: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

</style>